package org.noka.socketserver;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Date;

public class ClientUtil extends Thread{
	private Socket client;//客户端socket
	private ClientInterface NClient=null;//操作实例
	private Integer cs=5;//没有接收到数据的空闲时间，以分钟为单位
	public ClientUtil(Socket s,ClientInterface NClient,Integer cs){
		this.client=s;
		this.NClient = NClient;
		this.cs = cs;
	}
	public void run(){
		try{
			Date od = new Date();
			Boolean isrun=true;
			BufferedReader in =	new BufferedReader(new InputStreamReader(client.getInputStream()));
		    while(isrun){
		    	//------------接收数据-------------------------------------------
		    	try{
				    if(in.ready()){//有数据到达
				    	od=new Date();
				    	Boolean b=NClient.onReadData(client);	
				    	if(!b)
				    		isrun=false;
				    }else{
				    	Date nd=new Date();
				    	Long ns = (nd.getTime()-od.getTime()) / (1000*60);
				    	if(ns>cs){//超时
				    		isrun=NClient.onDisTimeout(client, ns);
				    		od=new Date();
				    	}
				    }
		    	}catch(Exception se){
		    		isrun=false;
		    		break;
		    	}
		    	Thread.sleep(300);
		    }
		    NClient.onUnConnection(client);
		    //------------关闭连接-------------------
		    if(client!=null){
		    	client.close();
		    	client=null;
		    }
		}catch(Exception d){
			//System.out.println(d);
			d.printStackTrace();
		}
	}
}
